package com.fita.admin.web.controller.agent;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.utils.WebUtils;
import com.fita.admin.entity.search.agent.AgentCompanySearch;
import com.fita.admin.entity.security.Login;
import com.fita.admin.service.agent.AgentCompanyService;
import com.fita.admin.service.agent.AgentService;
import com.fita.admin.service.authority.PrincipalService;
import com.fita.admin.service.wallet.UserWalletService;
import com.fita.admin.web.controller.authority.DistrictController;
import com.fita.admin.web.resolver.Secure;
import com.fita.entity.agent.Agent;
import com.fita.entity.agent.AgentCompany;
import com.fita.entity.principal.Principal;
import com.fita.entity.wallet.UserWallet;
import org.apache.commons.collections.ListUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代理列表
 *
 * @author cuteHU
 *
 */
@Controller
@RequestMapping("/agents")
@MenuSetting("menu-agent")
public class AgentController {

    private Logger logger = LoggerFactory.getLogger(DistrictController.class);

    @Autowired
    private AgentCompanyService agentCompanyService;

    @Autowired
    private AgentService agentService;

    @Autowired
    private PrincipalService principalService;

    @Autowired
    private UserWalletService userWalletService;

    /**
     * @param page
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-agent-list")
    public ModelAndView list(AgentCompanySearch search,
                             Page page,
                             @Secure Login login) {

        ModelAndView modelAndView = new ModelAndView("agent/agent/agent-list");

        // 不是admin添加district条件
        if (!login.isAdmin()){
            search.bindDistrictId(login.getDistrict().getId());
        }
        int totals = agentCompanyService.count(search);

        if (totals > 0) {

            List<AgentCompany> agentCompanies = agentCompanyService.search(AgentCompany.class, search, page.with(totals));

            modelAndView.addObject("agentCompanies", agentCompanies);

            List<Object[]> amounts = agentCompanyService.calculateSecondaryAgentAmount();

            Map amountMap = new HashMap<>();

            amounts.stream().forEach(e -> amountMap.put(e[0],  e[1]));

            modelAndView.addObject("amountMap", amountMap);

            modelAndView.addObject("page", page);
        }
        return modelAndView;
    }

    /**
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public ModelAndView search() {
        ModelAndView modelAndView = new ModelAndView("agent/agent/agent-search");
        List<Principal> principals = principalService.listSaleUser();
        modelAndView.addObject("principals", principals);
        return modelAndView;
    }

    /**
     * @param search
     * @param page
     * @param request
     * @return
     */
    @MenuSetting("submenu-agent-list")
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
    public ModelAndView onSearch(AgentCompanySearch search, Page page, HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView("agent/agent/agent-list");

        int totals = agentService.countSearch(AgentCompany.class, search.getPreparedFilter(false));

        if (totals > 0) {

            List<AgentCompany> agentCompanies = agentCompanyService.search(AgentCompany.class, search,
                    page.with(totals));
            modelAndView.addObject("agentCompanies", agentCompanies);

            modelAndView.addObject("page", page);

            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "filter", "page"));
        }
        return modelAndView;
    }

    /**
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable("id") Long id) {

        ModelAndView modelAndView = new ModelAndView("agent/agent/agent-edit");

        AgentCompany agentCompany = agentCompanyService.load(AgentCompany.class, id);

        modelAndView.addObject("agentCompany", agentCompany);

        return modelAndView;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onEdit(@PathVariable Long id, AgentCompany agentCompany) {

        HttpResult httpResult = new HttpResult();

        try {
            agentService.edit(id, agentCompany);
            httpResult.success().message("修改成功");
        } catch (BusinessException e) {
            logger.error("onEdit occurs error: ", e);
            httpResult.fail(e.getCode()).message(e.getMessage());
        } catch (Exception e) {
            logger.error("#onEdit() - agentCompany team fail, exception is [{}]", e);
            httpResult.fail("500").message("修改失败");
        }
        return httpResult;
    }

    /**
     * 详情
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @MenuSetting("submenu-agent-list")
    public ModelAndView view(@PathVariable Long id) {
        ModelAndView modelAndView = new ModelAndView("agent/agent/agent-view");

        AgentCompany agentCompany = agentCompanyService.load(AgentCompany.class, id);

        modelAndView.addObject("agentCompany", agentCompany);

        List<Agent> agents = agentService.list(agentCompany);

        List<Agent> secondaryAgents = agentService.listSecondaryAgent(id);

        modelAndView.addObject("agents", agents);

        UserWallet userWallet = userWalletService.loadByAgentCompanyId(id);

        modelAndView.addObject("userWallet", userWallet);

        modelAndView.addObject("secondaryAgents", secondaryAgents);

        return modelAndView;
    }

    /**
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/freeze-agent", method = RequestMethod.GET)
    public ModelAndView freezeAgent(@PathVariable Long id) {
        ModelAndView modelAndView = new ModelAndView("agent/agent/agent-freeze");
        modelAndView.addObject("id", id);
        return modelAndView;
    }

    /**
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/freeze-agent", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onFreezeAgent(@PathVariable("id") Long id) {
        HttpResult result = new HttpResult();
        try {

            Agent agent = agentService.load(Agent.class, id);

            agentService.freezeAgent(agent);

            result.success().message("冻结成功！");

        } catch (Exception e) {

            result.fail("500").message("冻结失败！");
        }

        return result;
    }

    /**
     * @param id
     * @return
     */

    @RequestMapping(value = "/{id}/activate-agent", method = RequestMethod.GET)
    public ModelAndView activateAgent(@PathVariable Long id) {
        ModelAndView modelAndView = new ModelAndView("agent/agent/agent-activate");
        modelAndView.addObject("id", id);
        return modelAndView;
    }

    /**
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/activate-agent", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onActivateAgent(@PathVariable("id") Long id) {
        HttpResult result = new HttpResult();
        try {

            Agent agent = agentService.load(Agent.class, id);

            agentService.activateAgent(agent);

            result.success().message("激活成功！");

        } catch (Exception e) {

            result.fail("500").message("激活失败！");
        }
        return result;
    }


    /**
     *
     * @param agentCompanyId
     * @param agentId
     * @return
     */
    @RequestMapping(value = "/{agentCompanyId}/agents/{agentId}", method = RequestMethod.GET)
    public ModelAndView editAgent(@PathVariable("agentCompanyId") Long agentCompanyId,
                                  @PathVariable("agentId") Long agentId) {

        ModelAndView modelAndView = new ModelAndView("agent/agent/agent-edit-agent");

        Agent agent = agentService.load(Agent.class, agentId);
        modelAndView.addObject("agentCompanyId",agentCompanyId);
        modelAndView.addObject("agent", agent);

        return modelAndView;
    }

    @RequestMapping(value = "/{agentCompanyId}/agents/{agentId}", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onEditAgents(@PathVariable("agentId") Long agentId, Agent agent) {

        HttpResult httpResult = new HttpResult();

        try {
            agentService.editAgent(agentId, agent);
            httpResult.success().message("修改成功");
        } catch (BusinessException e) {
            logger.error("onEdit occurs error: ", e);
            httpResult.fail(e.getCode()).message(e.getMessage());
        } catch (Exception e) {
            logger.error("#onEdit() - agent team fail, exception is [{}]", e);
            httpResult.fail("500").message("修改失败");
        }
        return httpResult;
    }

    /**
     * 修改指定销售
     *
     * @param agentCompanyId
     * @return
     */
    @RequestMapping(value = "/{agentCompanyId}/change-salesperson", method = RequestMethod.GET)
    public ModelAndView changeSalesperson(@PathVariable("agentCompanyId") Long agentCompanyId) {

        ModelAndView modelAndView = new ModelAndView("agent/agent/agent-change-salesperson");

        AgentCompany agentCompany = agentCompanyService.load(AgentCompany.class, agentCompanyId);

        List<Principal> principals = principalService.list(ListUtils.EMPTY_LIST, agentCompany.getDistrict());

        modelAndView.addObject("agentCompany", agentCompany);

        modelAndView.addObject("principals", principals);

        modelAndView.addObject("agentCompanyId", agentCompanyId);

        return modelAndView;
    }

    /**
     * 修改指定销售
     * @param agentCompanyId
     * @param principalId
     * @return
     */
    @RequestMapping(value = "/{agentCompanyId}/change-salesperson", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onChangeSalesperson(@PathVariable("agentCompanyId") Long agentCompanyId,
                                                        @RequestParam Long principalId) {
        HttpResult httpResult = new HttpResult();

        try {
            agentCompanyService.changeSalesperson(agentCompanyId, principalId);
            httpResult.success().message("修改成功");
        } catch (BusinessException e) {
            logger.error("#onEdit() occurs error: ", e);
            httpResult.fail(e.getCode()).message(e.getMessage());
        } catch (Exception e) {
            logger.error("#onEdit() - agent team fail, exception is [{}]", e);
            httpResult.fail("500").message("修改失败");
        }
        return httpResult;
    }

    /**
     * 允许成为一级代理
     * @param agentCompanyId
     * @return
     */
    @GetMapping(path = "/{agentCompanyId}/enable-primary-agent")
    public ModelAndView enablePrimaryAgent(@PathVariable Long agentCompanyId){

        ModelAndView modelAndView = new ModelAndView("agent/agent/agent-enable-primary-agent");

        modelAndView.addObject("agentCompanyId", agentCompanyId);

        return modelAndView;
    }

    /**
     * 允许成为一级代理
     * @return
     */
    @PatchMapping(path = "/{agentCompanyId}/enable-primary-agent", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public HttpResult onEnablePrimaryAgent(@PathVariable Long agentCompanyId){

        HttpResult httpResult = new HttpResult();

        agentCompanyService.enablePrimaryAgent(agentCompanyId);

        return httpResult.success();
    }


    /**
     * 禁止成为一级代理
     * @param agentCompanyId
     * @return
     */
    @GetMapping(path = "/{agentCompanyId}/disable-primary-agent")
    public ModelAndView disablePrimaryAgent(@PathVariable Long agentCompanyId){

        ModelAndView modelAndView = new ModelAndView("agent/agent/agent-disable-primary-agent");

        modelAndView.addObject("agentCompanyId", agentCompanyId);

        return modelAndView;
    }

    /**
     * 禁止成为一级代理
     * @return
     */
    @PatchMapping(path = "/{agentCompanyId}/disable-primary-agent", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public HttpResult onDisablePrimaryAgent(@PathVariable Long agentCompanyId){

        HttpResult httpResult = new HttpResult();

        agentCompanyService.disablePrimaryAgent(agentCompanyId);

        return httpResult.success();
    }



}
